package com.xnew.user.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xnew.bean.common.FileInfo;
import com.xnew.bean.common.IndvUserInfo;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.constant.Constant;
import com.xnew.encrypt.Sm3Encrypt;
import com.xnew.entity.ssoApi.*;
import com.xnew.exception.CustomException;
import com.xnew.org.mapper.OrgDeptInfoMapper;
import com.xnew.bean.common.AuUserRole;
import com.xnew.role.mapper.AuUserRoleMapper;
import com.xnew.ssoApi.mapper.SysUserInfoMapper;
import com.xnew.ssoApi.service.SsoApiService;
import com.xnew.user.mapper.AuUserMapper;
import com.xnew.user.mapper.IndvUserInfoMapper;
import com.xnew.user.service.IndvUserInfoService;
import com.xnew.utils.*;
import org.apache.shiro.crypto.hash.Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: hexs
 * @Project: JavaLaity
 * @Pcakage: com.xnew.user.service.impl.IndvUserInfoServiceImpl
 * @Date: 2022年05月19日 16:58
 * @Description:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class IndvUserInfoServiceImpl implements IndvUserInfoService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private IndvUserInfoMapper indvUserInfoMapper;

    @Resource
    private AuUserMapper auUserMapper;

    @Resource
    private AuUserRoleMapper auUserRoleMapper;

    @Resource
    private OrgDeptInfoMapper orgDeptInfoMapper;

    @Resource
    private SysUserInfoMapper sysUserInfoMapper;

    @Resource
    private SsoApiService ssoApiService;
    @Resource
    private SysUserInfoMapper t61SysUserInfoMapper;
    @Value("${SSO.subSystem1}")
    private String subSystem1 ; //	会员系统编号
    @Value("${SSO.subSystem2}")
    private String subSystem2 ; //	会员系统编号
    @Value("${SSO.Client_id}")
    private String Client_id ; //	系统编号
    private String access_token = "93BD3C6370B27082D8D57B1E9C7D3AB2CD97B493C3046ACBE7F82EE219F7C054" ; //

    @Override
    public DataOutput indvUserAdd(IndvUserInfo indvUserInfo, HttpServletRequest request) {
        DataOutput out = DataOutput.success();
        try {
            if (indvUserInfo==null){
                out.setCode(-90001);
                out.setMsg("保存失败,获取数据为空！");
                return out;
            }
            System.out.println("=====判断登录名（" + indvUserInfo.getLoginName() + "）是否存在==========");
            List<SysUserInfo> sysUserInfos = auUserMapper.selectByLoginName(indvUserInfo.getLoginName().trim());
            if (sysUserInfos.size()>0){
                out.setCode(-90001);
                out.setMsg("保存失败,登录名已存在，请重新输入！");
                return out;
            }
            System.out.println("=====判断邮箱（" + indvUserInfo.getEml() + "）是否存在==========");
            if(indvUserInfo.getEml()!=null){
                sysUserInfos = auUserMapper.selectByEml("",indvUserInfo.getEml().trim());
                if (sysUserInfos.size()>0){
                    out.setCode(-90001);
                    out.setMsg("保存失败,邮箱已存在，请重新输入！");
                    return out;
                }
            }
            System.out.println("=====判断证件号码（" + indvUserInfo.getDtcNo() + "）是否存在==========");
            if(indvUserInfo.getDtcNo()!=null){
                sysUserInfos = auUserMapper.selectByDtcNo("",indvUserInfo.getDtcNo().trim());
                if (sysUserInfos.size()>0){
                    out.setCode(-90001);
                    out.setMsg("保存失败,证件号码已存在，请重新输入！");
                    return out;
                }
            }
            SysUserInfo userInfo = UserUtil.getUserInfo(request);
            //个人用户信息
            indvUserInfo.setIndvUserNo(IdUtils.getIncreaseIdByNanoTime());//id
            indvUserInfo.setBeltoOrgId(userInfo.getOrgUserNo());//所属机构编号
            indvUserInfo.setCreatePsnNo(userInfo.getUserInfoNo());//创建人
            indvUserInfo.setCreateTime(DateUtil.now());//创建时间
            indvUserInfo.setUpdateTime(DateUtil.now());//创建时间
            indvUserInfoMapper.insert(indvUserInfo);
            //登录用户信息
            Map<String, Object> userParams = new HashMap<>();
            userParams.put("password",Constant.SET_PASSWD);
            userParams.put("loginName",indvUserInfo.getLoginName());
            //创建个人用户信息
            SysUserInfo sysUserInfo = new SysUserInfo();
            sysUserInfo.setUserName(indvUserInfo.getIndvUserName());//用户名
            sysUserInfo.setUserInfoNo(IdUtils.getIncreaseIdByNanoTime());//id
            sysUserInfo.setPerUserNo(indvUserInfo.getIndvUserNo());//个人用户信息id
            sysUserInfo.setOrgUserNo(userInfo.getOrgUserNo());//机构用户id
            sysUserInfo.setCreateUserNo(userInfo.getUserInfoNo());//创建人
            sysUserInfo.setCreateTime(DateUtil.now());//创建时间
            sysUserInfo.setModyTime(DateUtil.now());//修改时间
            sysUserInfo.setRegIp(InetAddress.getLocalHost().getHostAddress());//ip
            sysUserInfo.setLoginName(indvUserInfo.getLoginName());//登录名
            sysUserInfo.setUserState(Constant.USER_STATUS_CODE_0);//用户状态
            sysUserInfo.setUserType(Constant.USER_TYPE_CODE_01);//用户类型
            String salt = Sm3Encrypt.getSaltString();
            sysUserInfo.setSalt(salt);
            // 新密码
            String newPassword = Sm3Encrypt.encrypt(salt, (String)userParams.get("password"), (String)userParams.get("loginName"));
            System.out.println("=========================================================================");
            System.out.println("==========================="+newPassword+"===============================");
            System.out.println("=========================================================================");
            sysUserInfo.setPwd(newPassword);//初始密码
            auUserMapper.insert(sysUserInfo);
            //用户角色关联
            List<AuUserRole> auUserRoleList = indvUserInfo.getAuUserRoleList();
            ObjectMapper auUserRoleListObjectMapper = new ObjectMapper();
            auUserRoleList = auUserRoleListObjectMapper.convertValue(auUserRoleList, new TypeReference<List<AuUserRole>>() {});
            for (AuUserRole aur : auUserRoleList) {
                AuUserRole auUserRole = new AuUserRole();
                auUserRole.setAurId(IdUtils.getIncreaseIdByNanoTime());//id
                auUserRole.setAuId(sysUserInfo.getUserInfoNo());//用户编号
                auUserRole.setArId(aur.getArId());//角色编号
                auUserRole.setArName(aur.getArName());//角色名称
                auUserRole.setAurCreateUser(userInfo.getUserInfoNo());//创建人
                auUserRole.setAurCreateTime(DateUtil.now());//创建时间
                auUserRole.setAurType(Constant.USER_TYPE_CODE_01);//个人用户类型
                auUserRoleMapper.insert(auUserRole);
            }

            SysUserInfo oginUser = UserUtil.getUserInfo(request);
            String code = oginUser!=null && oginUser.getCode()!=null?oginUser.getCode().trim():null;
            String access_token = oginUser!=null && oginUser.getAccess_token()!=null?oginUser.getAccess_token().trim():null;
            if(code!=null && !code.equals("")){
                if(Client_id!=null && !Client_id.equals("")){
                    System.out.println("====推送门户开始====");
                    System.out.println("indvUserInfo:" + indvUserInfo.toString());
                    String[] subSystems = new String[]{subSystem1,subSystem2};
                    int userType = 1;
                    System.out.println("indvUserInfo.getBeltoOrgId():" + indvUserInfo.getBeltoOrgId());
                    if(indvUserInfo.getBeltoOrgId()!=null && indvUserInfo.getBeltoOrgId().equals("1")){
                        userType = 3;
                    }else{
                        System.out.println("indvUserInfo.getOrgDutyCode():" + indvUserInfo.getOrgDutyCode());
                        if(indvUserInfo.getOrgDutyCode()!=null && indvUserInfo.getOrgDutyCode().equals("04")){
                            subSystems = new String[]{subSystem1};
                        }
                    }
                    String orgName = indvUserInfo.getUnit()!=null && !indvUserInfo.getUnit().trim().equals("")?indvUserInfo.getUnit().trim():null;
                    String cartType = indvUserInfo.getDtcId()!=null && !indvUserInfo.getDtcId().trim().equals("")?indvUserInfo.getDtcId().trim():null;
                    String cartNo = indvUserInfo.getDtcNo()!=null && !indvUserInfo.getDtcNo().trim().equals("")?indvUserInfo.getDtcNo().trim():null;
                    String realName = indvUserInfo.getIndvUserName()!=null && !indvUserInfo.getIndvUserName().trim().equals("")?indvUserInfo.getIndvUserName().trim():null;
                    String phone = indvUserInfo.getMob()!=null && !indvUserInfo.getMob().trim().equals("")?indvUserInfo.getMob().trim():null;
                    String email = indvUserInfo.getEml()!=null && !indvUserInfo.getEml().trim().equals("")?indvUserInfo.getEml().trim():null;
                    String deptName = indvUserInfo.getDeptName()!=null && !indvUserInfo.getDeptName().trim().equals("")?indvUserInfo.getDeptName().trim():null;
                    String position = indvUserInfo.getUnitPostName()!=null && !indvUserInfo.getUnitPostName().trim().equals("")?indvUserInfo.getUnitPostName().trim():null;
                    String account  = indvUserInfo.getLoginName()!=null && !indvUserInfo.getLoginName().trim().equals("")?indvUserInfo.getLoginName().trim():null;

                    ResultDo obj = null;
                    if(realName==null || "".equals(realName)){
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("对不起，操作失败，用户姓名 为空！请稍后重试！");
                        throw  new CustomException(out.getCode(),out.getMsg());
                    }
                    if(phone==null || "".equals(phone)){
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("对不起，操作失败，移动电话 为空！请稍后重试！");
                        throw  new CustomException(out.getCode(),out.getMsg());
                    }
                    if(email==null || "".equals(email)){
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("对不起，操作失败，邮箱 为空！请稍后重试！");
                        throw  new CustomException(out.getCode(),out.getMsg());
                    }
                    if(userType==3){//监管账户
                        PlatformSupvRegVo reg = new PlatformSupvRegVo();
                        reg.setAccess_token(access_token);
                        reg.setOrgName(orgName);
                        reg.setRealName(realName);
                        reg.setPhone(phone);
                        reg.setEmail(email);
                        reg.setDeptName(deptName);
                        reg.setAccount(account);
                        reg.setSubSystems(subSystems);
                        obj = ssoApiService.PlatformSupvReg(reg);
                    }else{//个人账户
                        if(cartType==null || "".equals(cartType)){
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("对不起，操作失败，证件类型 为空！请稍后重试！");
                            throw  new CustomException(out.getCode(),out.getMsg());
                        }
                        if(cartNo==null || "".equals(cartNo)){
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("对不起，操作失败，证件号码 为空！请稍后重试！");
                            throw  new CustomException(out.getCode(),out.getMsg());
                        }
                        PlatformPersonalRegVo reg = new PlatformPersonalRegVo();
                        reg.setAccess_token(access_token);
                        reg.setOrgName(orgName);
                        reg.setCartType(cartType);
                        reg.setCartNo(cartNo);
                        reg.setRealName(realName);
                        reg.setPhone(phone);
                        reg.setEmail(email);
                        reg.setDeptName(deptName);
                        reg.setPosition(position);
                        reg.setUserType(userType);
                        reg.setSubSystems(subSystems);
                        obj = ssoApiService.PlatformPersonalReg(reg);
                    }
                    out.setMsg(obj.getMsg());
                    out.setCode(obj.getCode());
                    out.setData(ConvertEntityUtil.convertEntityData(obj));
                    String userInfoNo = null;
                    if(account!=null){
                        userInfoNo = account.trim();
                    }else{
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("与统一登录门户交互异常，loginName is null,请联系协会系统管理员！");
                        throw  new CustomException(out.getCode(),out.getMsg());
                    }
                    System.out.println("userInfoNo:" + userInfoNo);
                    if(userInfoNo!=null && !"".equals(userInfoNo.trim()) && obj.getCode()==200 ){
                        Object data = obj.getData();
                        Map<String,String> params = JSONObject.parseObject(data+"", Map.class);
                        if(params!=null){
                            String openId = params.get("openId")!=null?(String)params.get("openId"):"";
                            if(!openId.equals("")){
                                t61SysUserInfoMapper.updateByOpenId(userInfoNo,openId);
                            }else{
                                out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                out.setMsg("与统一登录门户交互异常,openId is null，请联系协会系统管理员！");
                                throw  new CustomException(out.getCode(),out.getMsg());
                            }
                        }else{
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("与统一登录门户交互异常，params is null,请联系协会系统管理员！");
                            throw  new CustomException(out.getCode(),out.getMsg());
                        }
                    }else{
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("与统一登录门户交互异常，请联系协会系统管理员！");
                        throw  new CustomException(out.getCode(),out.getMsg());
                    }
                    System.out.println("====推送门户结束====");

                }
            }

        }catch (Exception e){
            logger.error(e.getMessage(), e);
            out.setCode(-90001);
            out.setMsg("操作失败!" + out.getMsg());
        }
        return out;
    }

    @Override
    public IndvUserInfo queryIndvUser(String indvUserNo, HttpServletRequest request) {
        //个人用户信息
        IndvUserInfo indvUserInfo = indvUserInfoMapper.selectByIndvUserNo(indvUserNo);
        //个人用户与角色关联信息
        SysUserInfo sysUserInfo = auUserMapper.selectByPerUserNo(indvUserInfo.getIndvUserNo());
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("au_id", sysUserInfo.getUserInfoNo());
        List<AuUserRole> auUserRoles = auUserRoleMapper.selectByAuId(sysUserInfo.getUserInfoNo());
        indvUserInfo.setAuUserRoleList(auUserRoles);
        return indvUserInfo;
    }

    @Override
    public DataOutput indvUserUpdate(IndvUserInfo indvUserInfo, HttpServletRequest request) throws Exception {
        DataOutput out = DataOutput.success();
        boolean subSso = false;
        SysUserInfo userInfo = UserUtil.getUserInfo(request);
            List<SysUserInfo> sysUserInfos = null;
            if(indvUserInfo.getBeltoOrgId()!=null && indvUserInfo.getBeltoOrgId().equals("1") ){
                System.out.println("=====判断邮箱（" + indvUserInfo.getEml() + "）是否存在==========");
                if(indvUserInfo.getEml()!=null){
                    sysUserInfos = auUserMapper.selectByEml(indvUserInfo.getIndvUserNo(),indvUserInfo.getEml().trim());
                    if (sysUserInfos.size()>0){
                        out.setCode(-90001);
                        out.setMsg("保存失败,邮箱已存在，请重新输入！");
                        return out;
                    }else{
                        sysUserInfos = auUserMapper.selectByEml(null,indvUserInfo.getEml().trim());
                        if (sysUserInfos.size()<=0){
                            subSso = true;
                        }
                    }
                }
            }
            if(indvUserInfo.getBeltoOrgId()!=null  && !indvUserInfo.getBeltoOrgId().equals("") && !indvUserInfo.getBeltoOrgId().equals("1")){
                System.out.println("=====判断证件号码（" + indvUserInfo.getDtcNo() + "）是否存在==========");
                if(indvUserInfo.getDtcNo()!=null){
                    sysUserInfos = auUserMapper.selectByDtcNo(indvUserInfo.getIndvUserNo(),indvUserInfo.getDtcNo().trim());
                    if (sysUserInfos.size()>0){
                        out.setCode(-90001);
                        out.setMsg("保存失败,证件号码已存在，请重新输入！");
                        return out;
                    }else{
                        sysUserInfos = auUserMapper.selectByDtcNo(null,indvUserInfo.getDtcNo().trim());
                        if (sysUserInfos.size()<=0){
                            subSso = true;
                        }
                    }
                }
            }
            System.out.println("=====修改个人用户信息==========");
            indvUserInfo.setUpdatePsnNo(userInfo.getUserInfoNo());//修改人
            indvUserInfo.setUpdateTime(DateUtil.now());//修改时间
            indvUserInfoMapper.updateById(indvUserInfo);

            System.out.println("=====修改用户角色关联==========");
            SysUserInfo sysUserInfo = auUserMapper.selectByPerUserNo(indvUserInfo.getIndvUserNo());
            HashMap<String, Object> auIdMap = new HashMap<>();
            auIdMap.put("au_id", sysUserInfo.getUserInfoNo());

            System.out.println("=====修改登录用户用户信息==========");
            sysUserInfo.setUserName(indvUserInfo.getIndvUserName());//用户名
            sysUserInfo.setModyTime(DateUtil.now());//修改时间
            auUserMapper.updateById(sysUserInfo);

            System.out.println("=====删除角色关联==========");
            auUserRoleMapper.deleteByMap(auIdMap);

            System.out.println("=====新增角色关联==========");
            List<AuUserRole> auUserRoleList = indvUserInfo.getAuUserRoleList();
            ObjectMapper auUserRoleListObjectMapper = new ObjectMapper();
            auUserRoleList = auUserRoleListObjectMapper.convertValue(auUserRoleList, new TypeReference<List<AuUserRole>>() {});
            for (AuUserRole aur : auUserRoleList) {
                AuUserRole auUserRole = new AuUserRole();
                auUserRole.setAurId(IdUtils.getIncreaseIdByNanoTime());//id
                auUserRole.setAuId(sysUserInfo.getUserInfoNo());//用户编号
                auUserRole.setArId(aur.getArId());//角色编号
                auUserRole.setArName(aur.getArName());//角色名称
                auUserRole.setAurCreateUser(userInfo.getUserInfoNo());//创建人
                auUserRole.setAurCreateTime(DateUtil.now());//创建时间
                auUserRole.setAurType(Constant.USER_TYPE_CODE_01);//个人用户类型
                auUserRoleMapper.insert(auUserRole);
            }

            SysUserInfo oginUser = UserUtil.getUserInfo(request);
            String code = oginUser!=null && oginUser.getCode()!=null?oginUser.getCode().trim():null;
            String access_token = oginUser!=null && oginUser.getAccess_token()!=null?oginUser.getAccess_token().trim():null;
            if(code!=null && !code.equals("")){
                if(Client_id!=null && !Client_id.equals("")){
                    System.out.println("====推送门户开始====");
                    String openId  = indvUserInfo.getOpenId()!=null?!indvUserInfo.getOpenId().trim().equals("")?indvUserInfo.getOpenId().trim():null:null;
                    if(openId!=null && !subSso ){
                        System.out.println("====不需修改！推送门户结束====");
                        return out;
                    }
                    System.out.println("indvUserInfo:" + indvUserInfo.toString());
                    String[] subSystems = new String[]{subSystem1,subSystem2};
                    int userType = 1;
                    System.out.println("indvUserInfo.getBeltoOrgId():" + indvUserInfo.getBeltoOrgId());
                    if(indvUserInfo.getBeltoOrgId()!=null && indvUserInfo.getBeltoOrgId().equals("1")){
                        userType = 3;
                    }else{
                        System.out.println("indvUserInfo.getOrgAttrCode():" + indvUserInfo.getOrgAttrCode());
                        if(indvUserInfo.getOrgAttrCode()!=null && indvUserInfo.getOrgAttrCode().equals("04")){
                            subSystems = new String[]{subSystem1};
                        }
                    }
                    String orgName = indvUserInfo.getUnit()!=null?!indvUserInfo.getUnit().trim().equals("")?indvUserInfo.getUnit().trim():null:null;
                    String cartType = indvUserInfo.getDtcId()!=null?!indvUserInfo.getDtcId().trim().equals("")?indvUserInfo.getDtcId().trim():null:null;
                    String cartNo = indvUserInfo.getDtcNo()!=null?!indvUserInfo.getDtcNo().trim().equals("")?indvUserInfo.getDtcNo().trim():null:null;
                    String realName = indvUserInfo.getIndvUserName()!=null?!indvUserInfo.getIndvUserName().trim().equals("")?indvUserInfo.getIndvUserName().trim():null:null;
                    String phone = indvUserInfo.getMob()!=null?!indvUserInfo.getMob().trim().equals("")?indvUserInfo.getMob().trim():null:null;
                    String email = indvUserInfo.getEml()!=null?!indvUserInfo.getEml().trim().equals("")?indvUserInfo.getEml().trim():null:null;
                    String deptName = indvUserInfo.getDeptName()!=null?!indvUserInfo.getDeptName().trim().equals("")?indvUserInfo.getDeptName().trim():null:null;
                    String position = indvUserInfo.getUnitPostName()!=null?!indvUserInfo.getUnitPostName().trim().equals("")?indvUserInfo.getUnitPostName().trim():null:null;
                    String account  = indvUserInfo.getLoginName()!=null?!indvUserInfo.getLoginName().trim().equals("")?indvUserInfo.getLoginName().trim():null:null;
                    if(userType == 3){//监管账户
                        if(email==null){
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("对不起，操作失败，邮箱 为空！请稍后重试！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                    }else {//个人账户
                        if (cartType == null && cartNo == null) {
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("对不起，操作失败，证件类型和证件号码 为空！请稍后重试！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                        if (cartType == null) {
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("对不起，操作失败，证件类型 为空！请稍后重试！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                        if (cartNo == null) {
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("对不起，操作失败，证件号码 为空！请稍后重试！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                    }
                    ResultDo obj = null;
                    if(openId!=null && !openId.equals("")){
                        System.out.println("====账户修改====");
                        AccountVo reg = new AccountVo();
                        reg.setAccess_token(access_token);
                        reg.setOpenId(openId);
                        reg.setOrgName(orgName);
                        reg.setCartType(cartType);
                        reg.setCartNo(cartNo);
                        reg.setRealName(realName);
                        reg.setPhone(phone);
                        reg.setEmail(email);
                        reg.setUserType(userType);
                        reg.setSubSystems(subSystems);
                        obj = ssoApiService.Account(reg);
                        out.setMsg(obj.getMsg());
                        out.setCode(obj.getCode());
                        out.setData(ConvertEntityUtil.convertEntityData(obj));
                        String newOpenId = null;
                        String userInfoNo = null;
                        if(indvUserInfo.getLoginName()!=null){
                            userInfoNo = indvUserInfo.getLoginName();
                        }
                        if(userInfoNo!=null && !"".equals(userInfoNo.trim()) && obj.getCode()==200 ){
                            Object data = obj.getData();
                            Map<String,String> params = JSONObject.parseObject(data+"", Map.class);
                            if(params!=null){
                                openId = params.get("openId")!=null?(String)params.get("openId"):"";
                                newOpenId = params.get("newOpenId")!=null?(String)params.get("newOpenId"):"";
                                if(newOpenId.trim().equals("") && openId.equals(newOpenId)){
                                    t61SysUserInfoMapper.updateByOpenId(userInfoNo,newOpenId);
                                }
                            }else{
                                out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                out.setMsg("与统一登录门户交互异常，请联系协会系统管理员！");
                                throw new CustomException(out.getCode(), out.getMsg());
                            }
                        }else{
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("统一登录门户交互异常!" + obj.getMsg() + "!请联系协会系统管理员！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                    }else{
                        if(userType==3){//监管账户
                            System.out.println("====监管账户新建====");
                            PlatformSupvRegVo reg = new PlatformSupvRegVo();
                            reg.setAccess_token(access_token);
                            reg.setOrgName(orgName);
                            reg.setRealName(realName);
                            reg.setPhone(phone);
                            reg.setEmail(email);
                            reg.setDeptName(deptName);
                            reg.setAccount(account);
                            reg.setSubSystems(subSystems);
                            obj = ssoApiService.PlatformSupvReg(reg);
                        }else{//个人账户
                            System.out.println("====个人账户新建====");
                            PlatformPersonalRegVo reg = new PlatformPersonalRegVo();
                            reg.setAccess_token(access_token);
                            reg.setSubSystems(subSystems);
                            reg.setOrgName(orgName);
                            reg.setCartType(cartType);
                            reg.setCartNo(cartNo);
                            reg.setRealName(realName);
                            reg.setPhone(phone);
                            reg.setEmail(email);
                            reg.setDeptName(deptName);
                            reg.setPosition(position);
                            reg.setUserType(userType);
                            obj = ssoApiService.PlatformPersonalReg(reg);
                        }
                        out.setMsg(obj.getMsg());
                        out.setCode(obj.getCode());
                        out.setData(ConvertEntityUtil.convertEntityData(obj));
                        String userInfoNo = null;
                        if(account!=null){
                            userInfoNo = account.trim();
                        }else{
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("与统一登录门户交互异常，loginName is null,请联系协会系统管理员！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                        System.out.println("userInfoNo:" + userInfoNo);
                        if(userInfoNo!=null && !"".equals(userInfoNo.trim()) && obj.getCode()==200 ){
                            Object data = obj.getData();
                            Map<String,String> params = JSONObject.parseObject(data+"", Map.class);
                            if(params!=null){
                                openId = params.get("openId")!=null?(String)params.get("openId"):"";
                                if(!openId.equals("")){
                                    t61SysUserInfoMapper.updateByOpenId(userInfoNo,openId);
                                }else{
                                    out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                    out.setMsg("与统一登录门户交互异常,openId is null，请联系协会系统管理员！");
                                    throw new CustomException(out.getCode(), out.getMsg());
                                }
                            }else{
                                out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                out.setMsg("与统一登录门户交互异常，params is null,请联系协会系统管理员！");
                                throw new CustomException(out.getCode(), out.getMsg());
                            }
                        }else{
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("与统一登录门户交互异常!" + obj.getMsg() + "!请联系协会系统管理员！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }

                    }
                    System.out.println("====推送门户结束====");
                }
            }
        return out;
    }

    @Override
    public void deleteIndvUser(String perUserNo, HttpServletRequest request) {
        indvUserInfoMapper.deleteById(perUserNo);
        auUserMapper.deleteByPerUserNo(perUserNo);
        auUserRoleMapper.deleteByAuId(perUserNo);
    }
    @Override
    public DataOutput deleteIndvUser(String userInfoNo,String perUserNo,String openId,
                                     HttpServletRequest request) throws Exception {
        DataOutput out = DataOutput.success();
            indvUserInfoMapper.deleteById(perUserNo);
            auUserRoleMapper.deleteByUserInfoNo(userInfoNo);
            sysUserInfoMapper.deleteById(userInfoNo);

            SysUserInfo oginUser = UserUtil.getUserInfo(request);
            String code = oginUser!=null && oginUser.getCode()!=null?oginUser.getCode().trim():null;
            String access_token = oginUser!=null && oginUser.getAccess_token()!=null?oginUser.getAccess_token().trim():null;
            if(code!=null && !code.equals("")){
                if(Client_id!=null && !Client_id.equals("")){
                    System.out.println("====推送门户开始====");
                    String[] subSystems = new String[]{subSystem1,subSystem2};
                    OrgAccountStateVo reg = new OrgAccountStateVo();

                    //reg.setAccess_token((String)param.get("access_token"));//是 token
                    reg.setOpenId(openId);//用户 openId
                    reg.setAccess_token(access_token);
                    reg.setSubSystems(subSystems);
                    reg.setState(3);
                    ResultDo obj = ssoApiService.OrgAccountState(reg);
                    if(obj!=null){
                        out.setMsg(obj.getMsg());
                        out.setCode(obj.getCode());
                        out.setData(ConvertEntityUtil.convertEntityData(obj));
                        if(obj.getCode()!=200 ){
                            out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                            out.setMsg("与统一登录门户交互异常!" + obj.getMsg() + "!请联系协会系统管理员！");
                            throw new CustomException(out.getCode(), out.getMsg());
                        }
                    }else{
                        out.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        out.setMsg("与统一登录门户交互异常!" + "返回报文为空" + "!请联系协会系统管理员！");
                        throw new CustomException(out.getCode(), out.getMsg());
                    }
                    System.out.println("====推送门户结束====");
                }
            }
        return out;
    }
    @Override
    public DataOutput updateUserState(String userInfoNo,String State) throws Exception {
        DataOutput out = DataOutput.success();
        sysUserInfoMapper.updataUserByStatus(userInfoNo,State);
        return out;
    }

    /**
     * 获取当前部门信息
     * @param userInfo
     * @return
     */
    @Override
    public List<Map<String, String>> getCurrentDeptInfo(SysUserInfo userInfo) {
        return orgDeptInfoMapper.getCurrentDeptInfo(userInfo.getAoiOrgNo());
    }

    /**
     * 查询角色用户列表
     * @param input
     * @return
     */
    @Override
    public List<SysUserInfo> querySysRoleUserList(DataInput input) {
        //使用PageHelper 进行分页处理
        PageHelper.startPage(input.getPageNum(), input.getPageSize());
        return auUserMapper.selectRoleIndvUserList(input.getParam());
    }

    @Override
    public List<Map<String, Object>> queryIndvUserDept(SysUserInfo userInfo) {
        return indvUserInfoMapper.queryIndvUserDept(userInfo.getOrgUserNo());
    }
}
